package com.mallcai.bigdata.ladon.dpl.mapper.system.provider;

import com.mallcai.bigdata.ladon.dpl.entity.system.RoleRlResource;
import com.mallcai.bigdata.ladon.dpl.mapper.BaseSqlProvider;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.jdbc.SQL;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author gst
 * @date 2019-12-30 20:36
 */
public class RoleRlResourceSqlProvider extends BaseSqlProvider<RoleRlResource> {
    public static final String TB_ROLE_RL_RESOURCE = "sys_role_rl_resource";

    /**
     * 获取表名
     *
     * @return String
     */
    @Override
    public String getTableName() {
        return TB_ROLE_RL_RESOURCE;
    }

    /**
     * 获取插入数据的字段列表
     *
     * @return Map
     */
    @Override
    public Map<String, String> getInsertColumns() {
        Map<String, String> map = new LinkedHashMap<>();
        map.put("role_id", "#{roleId}");
        map.put("res_id", "#{resId}");
        map.put("mask", "#{mask}");
        return map;
    }

    /**
     * 获取更新操作的字段列表
     *
     * @return Map
     */
    @Override
    public Map<String, String> getUpdateColumns() {
        Map<String, String> map = new LinkedHashMap<>();
        map.put("resId", "res_id");
        map.put("roleId", "role_id");
        map.put("mask", "mask");
        return map;
    }

    public String getByRoleIds(@Param("roleIds") List<Long> roleIds) {
        StringBuilder sb = new StringBuilder();
        sb.append("archive = 0");
        if (roleIds != null && roleIds.size() > 0) {
            sb.append(" AND role_id IN (");
            for (int i = 0; i < roleIds.size(); i++) {
                if (i > 0) {
                    sb.append(", ");
                }
                sb.append(roleIds.get(i));
            }
            sb.append(" )");
        } else {
            sb.append(" AND 1 = 0");
        }
        return new SQL() {
            {
                SELECT("*");
                FROM(getTableName());
                WHERE(sb.toString());
            }
        }.toString();
    }

    public String getOptResourceInfo(@Param("userId") Long userId) {
        StringBuilder sb = new StringBuilder();
        sb.append(" tb_r.path IS NOT NULL ")
                .append(" AND tb_rrr.archive = 0 ")
                .append(" AND tb_r.archive = 0 ")
                .append(" AND tb_rrr.role_id IN (")
                .append("    SELECT DISTINCT role_id FROM ")
                .append(UserRlRoleSqlProvider.TB_USER_RL_ROLE)
                .append(" WHERE archive = 0  AND user_id =")
                .append(" #{userId}")
                .append(" )");

        return new SQL() {
            {
                SELECT("tb_r.path, tb_rrr.*");
                FROM(getTableName() + " tb_rrr");
                LEFT_OUTER_JOIN(ResourceSqlProvider.TB_RES + " tb_r ON tb_rrr.res_id = tb_r.id");
                WHERE(sb.toString());
            }
        }.toString();
    }
}
